#!/usr/bin/env python
#
# Copyright 2012 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import httplib2
import logging
import os
import pickle

from apiclient.discovery import build
from oauth2client.appengine import oauth2decorator_from_clientsecrets
from oauth2client.client import AccessTokenRefreshError
from google.appengine.api import memcache
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp import util

# CLIENT_SECRETS, name of a file containing the OAuth 2.0 information for this
# application, including client_id and client_secret, which can be downloaded
# from google.
#
# And also on the API Access tab on the Google APIs Console
# <https://code.google.com/apis/console>
CLIENT_SECRETS = os.path.join(os.path.dirname(__file__),
    'secrets/client_secrets.json')

# Singleton service apis.
http = httplib2.Http(memcache)
plus_service = build("plus", "v1", http=http)

# TODO(jlapenna): Figure out what's going on with redirect_uris not using
# https.
plus_oauth_decorator = oauth2decorator_from_clientsecrets(
    CLIENT_SECRETS,
    scope=[
      'https://www.googleapis.com/auth/plus.me',
    ],
    message="You need a secrets file, dude.")


class ProfileHandler(webapp.RequestHandler):
  """Simple handler to display a user's name."""

  @plus_oauth_decorator.oauth_required
  def get(self):
    http = plus_oauth_decorator.http()
    user = plus_service.people().get(userId='me').execute(http=http)
    text = 'Hello, %s!' % user['displayName']
    self.response.out.write('%s' % (text,))


class MessageHandler(webapp.RequestHandler):
  """Handler used by the appengine app to load a message."""

  def get(self):
    # Set the cross origin resource sharing header to allow AJAX
    self.response.headers.add_header("Access-Control-Allow-Origin", "*")
    # Print some JSON
    self.response.out.write('{"message":"Good bye!"}\n')


app = webapp.WSGIApplication([
  ('/profile', ProfileHandler),
  ('/message', MessageHandler),
  (plus_oauth_decorator.callback_path,
  plus_oauth_decorator.callback_handler()),
  ], debug=True)
